const data = { foo: 1 }
let activeEffect = null 
const bucket = new WeakMap()
let effectStack = []
const effect = (fn, options = {}) => {
    const effectFn = () => {
        clearup(effectFn)
        activeEffect = effectFn
        effectStack.push(activeEffect)
        fn()
        effectStack.pop()
        activeEffect = effectStack[effectStack.length -1]
    }
    effectFn.deps = []
    effectFn.options = options
    effectFn()
}
const clearup = (effectFn) => {
    for (let i = 0; i < effectFn.deps.length; i++) {
        const deps = effectFn.deps[i]
        deps.delete(effectFn)
    }
    effectFn.deps.length = 0
}
const track = (target, key) => {
    let depsMap = bucket.get(target)
    if (!depsMap) bucket.set(target, depsMap = new Map())
    let deps = depsMap.get(key)
    if (!deps) depsMap.set(key, deps = new Set())
    deps.add(activeEffect)
    activeEffect.deps.push(deps)
} 
const trigger = (target, key) => {
    const depsMap = bucket.get(target)
    if (!depsMap) return true
    const effects = depsMap.get(key)
    const effectsToRun = new Set()
    effects && effects.forEach(fn => {
        if (activeEffect !== fn) {
            effectsToRun.add(fn)
        }
    })
    // 找一个方法 能在foreach 里面进行 delete add 
    
    // 收集到的fn 执行  fn执行  会重新建立依赖关系 删除 添加 删除 添加
    effectsToRun && effectsToRun.forEach(effectFn => {
        // 有scheduler 就 使用 scheduler 
        if (effectFn.options && effectFn.options.scheduler) {
            effectFn.options.scheduler(effectFn)
        } else {
            effectFn()
        }
    });
}
const obj = new Proxy(data, {
    get(target, key) {
        if (!activeEffect) return target[key]
        // 追踪的核心 
        track(target, key)
        return target[key]
    },
    set(target, key, newVale) {
        target[key] = newVale
        // 触发的逻辑
        trigger(target, key)
    }   
})
let jobQuene = new Set()
let isFlushing = false
const p = Promise.resolve()
let flushJob = () => {
    if (isFlushing) return 
    isFlushing = true 
    p.then(() => {
        jobQuene.forEach(fn => fn())
    }).finally(() => isFlushing = true)
}
effect(() => {
       console.log(obj.foo)
}, {
    scheduler(fn) {
        jobQuene.add(fn) 
        // 怎么让俩次进来执行一次 
        flushJob()
    }
})
obj.foo++
obj.foo++
// console.log('完结~')